import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
from scipy import stats
import os
script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir)
#加载数据
df = pd.read_csv('NotClean_EVUsage_Data.csv')
# 首先，我们将这些列转换为数值类型
df['Energy (kWh)'] = pd.to_numeric(df['Energy (kWh)'], errors='coerce')
df['GHG Savings (kg)'] = pd.to_numeric(df['GHG Savings (kg)'], errors='coerce')

# 计算每列的均值和标准差
mean_energy = df['Energy (kWh)'].mean()
std_energy = df['Energy (kWh)'].std()
mean_ghg = df['GHG Savings (kg)'].mean()
std_ghg = df['GHG Savings (kg)'].std()

# 定义异常值检测的阈值，通常使用 3σ 规则
z_scores_energy = np.abs(stats.zscore(df['Energy (kWh)']))
z_scores_ghg = np.abs(stats.zscore(df['GHG Savings (kg)']))

# 找出超过3σ的异常值
outliers_energy = df[z_scores_energy > 3]
outliers_ghg = df[z_scores_ghg > 3]

# 打印异常值
print("Energy (kWh) outliers:")
print(outliers_energy)

print("\nGHG Savings (kg) outliers:")
print(outliers_ghg)

# 可视化异常值
import matplotlib.pyplot as plt

plt.figure(figsize=(12, 5))

# 绘制能量消耗的箱型图
plt.subplot(1, 2, 1)
sns.boxplot(x=df['Energy (kWh)'])
plt.title('Energy Consumption Boxplot')

# 绘制GHG减排的箱型图
plt.subplot(1, 2, 2)
sns.boxplot(x=df['GHG Savings (kg)'])
plt.title('GHG Savings Boxplot')

plt.tight_layout()
plt.show()